﻿using System;
using System.Management.Automation;
using DotNet.DevOps.Tasks.Util;
using Microsoft.Build.Framework;

namespace DotNet.DevOps.Tasks.Network
{
    public interface IHostname
    {
        string Machine { get; set; }
        string Name { get; set; }
    }

    /// <summary>
    /// Retreives the hostname (NET-BIOS name) of a machine from an IP address or a DNS name. Stores the result in the output variable Name.
    /// </summary>
    /// <example>
    /// import-module .\DotNet.DevOps.Tasks.dll
    /// 
    /// $task = New-Object DotNet.DevOps.Tasks.Network.Hostname -Property @{
    ///                                                             Machine="192.168.1.100" 
    ///                                                        }
    /// $result = $task.Execute()
    /// $netbiosName = $task.Name
    /// </example> 
    /// <example>
    /// <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    /// 
    ///  <Import Project="$(libs)\DotNet.DevOps.Tasks.Targets" />
    /// 
    ///  <Target Name="Build">
    /// 
    ///    <Hostname Machine="192.168.1.100">
    ///      <Output TaskParameter="Name" PropertyName="Host" />
    ///    </Hostname>
    /// 
    ///    <Message Text="Hostname: $(Host)" />
    /// 
    ///  </Target>
    /// 
    /// </Project>
    /// </example>   
    public class Hostname : ITask, IHostname
    {
        public IBuildEngine BuildEngine { get; set; }
        public ITaskHost HostObject { get; set; }

        private string _machine;
        /// <summary>
        /// Name or IP address of machine to resolved the hostname (NET-BIOS name) from.
        /// </summary>
        [Required]
        public string Machine
        {
            get
            {
                return string.IsNullOrWhiteSpace(_machine) == true ? Environment.MachineName : _machine;
            }

            set { _machine = value; }
        }
        /// <summary>
        /// Resulting hostname (NET-BIOS name).
        /// </summary>
        [Output]
        public string Name { get; set; }

        private ILog Log { get; set; }

        public Hostname()
        {
            Log = new MSBuildLogger(this);
        }

        public Hostname(ILog log)
        {
            Log = log;
        }

        public bool Execute()
        {
            try
            {
                Name = System.Net.Dns.GetHostEntry(Machine).HostName;
            }
            catch (Exception e)
            {
                Log.LogError(e);
                return false;
            }
            return true;
        }
    }
}
